from object import Object
from eventServer import eventServer

class InputMap(Object):
    def __init__(self):
        Object.__init__(self)
        
        self.defaultVar("binThreshold",0.5)
        self.defaultVar("player",0)
        
        eventServer.register("keyDown",self.keyDown)
        eventServer.register("keyUp",self.keyUp)
        eventServer.register("mouseButtonDown",self.mouseButtonDown)
        eventServer.register("mouseButtonUp",self.mouseButtonUp)
        eventServer.register("joyButtonDown",self.joyButtonDown)
        eventServer.register("joyButtonUp",self.joyButtonUp)
        eventServer.register("joyAxisMotion",self.joyAxisMotion)
        
        from keys import keys
        self.reverseKeys = {}
        for key, val in keys.iteritems():
            self.reverseKeys[val] = key
        
    def processEvent(self, keys, value, bin):
        for key in keys:
            if self.hasVar(key):
                player = self.getVar("player")
                eventServer.pull(self.getVar(key),{"value":value,"bin":bin,"player":player})
        
    def keyDown(self, cmd, args):
        key = args['key']
        keys = ["key_%d" % key, "key_%s" % args['keyChar']]
        if self.reverseKeys.has_key(key):
            keys.append("key_%s" % self.reverseKeys[key])
        self.processEvent(keys,1.0,True)

    def keyUp(self, cmd, args):
        key = args['key']
        keys = ["key_%d" % key, "key_%s" % args['keyChar']]
        if self.reverseKeys.has_key(key):
            keys.append("key_%s" % self.reverseKeys[key])
        self.processEvent(keys,0.0,False)
        
    def mouseButtonDown(self, cmd, args):
        self.processEvent(['mouseButton_%d' % args['button']],1.0,True)

    def mouseButtonUp(self, cmd, args):
        self.processEvent(['mouseButton_%d' % args['button']],0.0,False)
        
    def joyButtonDown(self, cmd, args):
        self.processEvent(['joyButton_%d_%d' % (args['joy'],args['button'])],1.0,True)

    def joyButtonUp(self, cmd, args):
        self.processEvent(['joyButton_%d_%d' % (args['joy'],args['button'])],0.0,False)
        
    def joyAxisMotion(self, cmd, args):
        value = args['value']
        if value < 0:
            tag = 'neg'
            value *= -1
        else:
            tag = 'pos'
        bin = value > self.getVar("binThreshold")
        key = 'joyAxis_%s_%d_%d' % (tag,args['joy'],args['axis'])
        self.processEvent([key],value,bin)
